<template>
   <el-dialog append-to-body v-model="dialogVisible" :title="title" width="70%">
    <el-container class="library">
      <el-header>
        <el-row>
          <el-col :span="18">
            <el-button type="primary" :icon="Upload" @click="handleUpload">上传{{ props.type == FileType.Image ? '图片' :'视频' }}</el-button>
            <el-button @click="handleCategoryAdd" class="add" plain>添加分类</el-button>
          </el-col>
          <el-col :span="6">
            <el-input v-model="query.entity.name" placeholder="请输入名称" class="wd300" :prefix-icon="Search" maxlength="20" clearable @keyup.enter="loadFile" @clear="loadFile" />
          </el-col>
        </el-row>
        <el-divider />
      </el-header>
      <el-container>
        <el-aside>
          <div class="category">
            <ul>
              <li v-for="(item , index) in categorys" :class="{active: selectCategory.id === item.id }" @click="handleChangeCategory(item)" :key="index">
                <span class="name">{{ item.name }}</span>
                <span v-if="selectCategory.id !== item.id || index === 0" class="count">({{ item.fileCount }})</span>
                <span v-else class="operation">
                  <el-button @click="handleCategoryUpdate(item)" type="text"> <Edit class="editor pointer" /> </el-button>
                  <el-popconfirm :width="300"  @confirm="handleDeleteCategory(item.id)" title="确定要删除吗?仅删除分组，不删除图片，组内图片将自动归入未分组">
                    <template #reference>
                      <el-button type="text"> <Delete class="delete pointer" /></el-button>
                    </template>
                  </el-popconfirm>
                </span>
              </li>
            </ul>
          </div>
        </el-aside>
        <el-main class="list">
          <div class="filelist">
            <ul>
              <li v-for="item of list" @click.stop="handlefile(item)" :key="item.id">
                <el-image v-if="props.type === FileType.Image" :src="commonStore.setting.fileDomain + item.path" fit="scale-down" />
                <el-image v-else :src="commonStore.setting.fileDomain + item.cover" fit="scale-down" />
                <span v-if="item.number" class="number">{{ item.number }}</span>
                <p>{{ item.name }}</p>
                <ZoomIn @click.stop="handleView(item)" v-if="props.type === FileType.Image" class="icon-zoom" />
                <View @click.stop="handleView(item)" v-else class="icon-zoom" />
              </li>
            </ul>
          </div>
          <footer v-if="total" class="filefooter">
            <div class="operation">
              <el-button class="deletefile" size="small" @click="handleDeleteFile">批量删除</el-button>
            </div>
            <div class="pagination">
              <el-pagination background @current-change="handleCurrentChange" v-model:current-page="query.page.index" :page-size="query.page.size" layout="total,prev,pager, next" :total="total" />
            </div>
          </footer>
        </el-main>
      </el-container>
    </el-container>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </span>
    </template>
   </el-dialog> 
   <image-upload v-model:visible="imageVisible" :category='selectCategory.id'   @on-confirm="onImageConfirm" />
   <video-upload v-model:visible="videoVisible" :category='selectCategory.id'  @on-confirm="onVideoConfirm" />
   <!--添加分类-->
   <el-dialog append-to-body v-model="categoryForm.dialogVisible" :title="categoryForm.title" width="400px">
      <el-form ref="categoryFormRef" label-width="150px" class="ruleForm" :model="categoryForm.form" :rules="categoryForm.rules">
        <el-form-item label="分类名称：" prop="name">
          <el-col :span="22">
            <el-input v-model="categoryForm.form.name" maxlength="6" show-word-limit placeholder="最多可输入6个字符" />
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryForm.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySave(categoryFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--添加分类 end-->
    <el-image-viewer v-if="viewForm.imageDialogVisible" :url-list="[commonStore.setting.fileDomain + viewForm.form.path]" @close="viewForm.imageDialogVisible = false" />
      <!--查看视频-->
  <el-dialog  width="600px" v-model="viewForm.videoDialogVisible">
    <video style="max-width:560px" controls :src="commonStore.setting.fileDomain  + viewForm.form.path" :autoplay="true"></video>
  </el-dialog>
    <!--查看视频 end-->
</template>
<script lang="ts" setup>
import { Upload,Search ,Edit,Delete,ZoomIn,View } from '@element-plus/icons-vue'
import { FileType } from '@/utils/enum'
import { ref,computed,watch,onMounted } from 'vue'
import  ImageUpload from '@/components/File/ImageUpload.vue'
import  VideoUpload from '@/components/File/VideoUpload.vue'
import {FileCategorys,Files,FileCategoryRemove, FileCategorySave, FileRemove, SetFileName,SetFileGroup} from '@/api/file'
import { ElForm,ElMessage,ElMessageBox } from 'element-plus'
import { useCommonStore } from '@/stores/common'
const commonStore  = useCommonStore()
const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: Number,
      default: FileType.Image
    },
    limit: {
      type: Number,
      default: 15
    }
})

const title = ref<string>('选择图片')
//选中的文件
const files = ref<FileView[]>([]) 
const imageVisible = ref<boolean>(false)
const videoVisible = ref<boolean>(false)
const categorys = ref<FileCategory[]>([])
const list = ref<FileView[]>([])
const total = ref<number>(0)
/**
 * 查询条件
 */
 const query =ref<PageModel<FileQuery>>({
  orderbyName: '',
  isAsc: false,
  beginDateTime: '',
  endDateTime: '',
  entity: {
    type: FileType.Image,
    name: '',
    categoryId: 0
  },
  page: {
      index: 1,
      size: 12
  }
})
const selectCategory = ref<any>({
    id :0,
    name:'未分组'

})
type FormInstance = InstanceType<typeof ElForm>
const categoryFormRef = ref<FormInstance>()
/**
 * 添加分类
 */
 const categoryForm = ref<DialogForm<FileCategory>>({
   dialogVisible: false,
   title:'添加分类',
   form: {
    id : 0,
    type : query.value.entity.type,
    name :'',
    fileCount: 0
   },
    rules: {
      name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
    }
})
/**
 * 游览文件
 */
const viewForm = ref <any>(
  {
    imageDialogVisible: false,
    videoDialogVisible: false,
    form: {
      id: 0,
      categoryId: 0,
      cover: '',
      name: '',
      size:0,
      path: ''
    }
  }
)



/**
 * 上传文件
 */
const handleUpload = ():void => {
  if(props.type == FileType.Image)
    imageVisible.value = true
  else
    videoVisible.value = true
}
/**
 * 上传图片成功
 * @param list  选中的文件
 */
const onImageConfirm = (list:FileEditor[]):void => {
  imageVisible.value = false
  query.value.page.index = 1
  loadCategory()
  loadFile()
}
/**
 * 上传视频成功
 * @param list  选中的文件
 */
const onVideoConfirm = (list:FileEditor):void => {
  videoVisible.value = false
  query.value.page.index = 1
  loadCategory()
  loadFile()
}

/**
 * 加载分类
 */
const loadCategory = ():void => { 
  FileCategorys(query.value.entity.type).then((res:ServiceResponse<FileCategory[]>) => {
    categorys.value = res.data ?? []
  })
}
/**
 * 加载列表
 */
 const loadFile = ():void => {
  Files(query.value).then((res:ServiceResponse<FileView[]>) => {
    if(res.success) {
      list.value = res.data ?? []
      total.value = res.count ?? 0
      ResetLists()
    }
  })
}
/**
 * 切换分类
 * @param id 
 */
const handleChangeCategory = (item:FileCategory):void => {
  selectCategory.value.id = item.id
  selectCategory.value.name = item.name
  query.value.entity.categoryId =  item.id
  loadFile()
}
/**
 * 修改分类
 * @param row 
 */
const handleCategoryUpdate = (row:FileCategory) : void => {
  categoryForm.value.title ='编辑分类'
  categoryForm.value.dialogVisible = true
  categoryForm.value.form.id = row.id
  categoryForm.value.form.name = row.name
}
/**
 * 添加分类
 */
const handleCategoryAdd = () : void => {
  categoryForm.value.title ='添加分类'
  categoryForm.value.dialogVisible = true
  categoryForm.value.form.id = 0
  categoryForm.value.form.name = ''
}
/**
 * 删除分类
 */
 const handleDeleteCategory = (id:number) :void => {
  FileCategoryRemove(id).then((res:any) =>{
   if (res.success) {
       loadCategory()
        query.value.page.index =1
        query.value.entity.categoryId = 0
        selectCategory.value.id = 0
        selectCategory.value.name = '未分组'
        loadFile()
        ElMessage.success('删除成功')
      } else return ElMessage.error(res.msg)
 })
}
/**
 * 保存分类
 */
 const handleCategorySave = (formEl: FormInstance | undefined): void => {
 if (!formEl) return
 formEl.validate((valid) => {
   if (valid) {
    FileCategorySave(categoryForm.value.form).then((res: any) => {
        if (res.success) {
        categoryForm.value.dialogVisible = false
        ElMessage.success('操作成功')
          loadCategory()
        } else {
        return ElMessage.error(res.msg)
        }
      })
   }
 })
}
/**
 * 选中图片
 */
const handlefile = (item:FileView):void => {
  if (item.checked) {
    files.value.forEach((file:FileView, index:Number, arr:any) => {
      if (file.id === item.id) {
        arr.splice(index, 1)
      }
    })
  } else {
    if(props.limit > 1){
      if(files.value.length < props.limit)
      files.value.push(item)
    }
    else {
      files.value=[item]
    }
  }
  ResetLists()
}
const ResetLists = ():void => {
    list.value.forEach((item:FileView) => {
        item.checked = false
        item.number = 0
    })
    if(files.value.length > 0){
      files.value.forEach((item:FileView, index:number) => {
        var selectFiles =  list.value.filter((p:FileView) => p.id == item.id)
        if(selectFiles.length > 0)
        {
            selectFiles[0].checked = true
            selectFiles[0].number = index + 1
        }
      })
    }    
}
/**
 * 删除分组
 */
const handleDeleteFile =(id : number):void => {
  if(files.value.length === 0 ) {
    ElMessage.error(`请选择${props.type === FileType.Image ? '图片':'视频'}`)
    return
  }
  let ids:number[] =[]
  files.value.forEach((item:FileView)=>{ids.push(item.id)})
  ElMessageBox.confirm(
      '确定要删除吗?',
      '提示',
      {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      }
  ).then(() => {
    
    const postForm :BatchEdior = {
      ids:ids,
      type:props.type,
      categoryId:0
    }
    FileRemove(postForm).then((res:any) => {
          if (res.success) {
          ElMessage.success('操作成功')
          loadCategory()
          loadFile()
          } else ElMessage.error(res.msg)
    })
  }).catch(() => {})
}

//分页
const handleCurrentChange = (currentPage:number):void => {
    query.value.page.index = currentPage 
    loadFile()
}

/**
 * 点击查看文件
 */
const handleView =(item:FileView):void => {
  
  if(props.type == FileType.Image)
  {
    viewForm.value.imageDialogVisible = true
    viewForm.value.videoDialogVisible = false
  } 
  else   {
    viewForm.value.imageDialogVisible = false
    viewForm.value.videoDialogVisible = true
  }
  viewForm.value.form = item
  console.log(viewForm.value)
}

/**
 * 点击确定
 */
const handleSave =():void => {
  dialogVisible.value = false
  dialogVisible.value = false
  let paths:any = []
  if(props.type === FileType.Image)
    files.value.forEach((item:any) => {paths.push(item.path)})
  else
    files.value.forEach((item:any) => {paths.push({path : item.path ,cover : item.cover})})
  emit('on-confirm', paths)
}

//定义事件
interface Emits {
  (e: 'update:visible', dialogVisible: boolean): void,
  (e: 'on-confirm', value: any ): void
}
const emit = defineEmits<Emits>()
const dialogVisible = computed({
  get() {
      return props.visible
  },
  set(visible: boolean) {
      emit('update:visible', visible)
  }
})
watch(()=>props.visible,(n,o) =>{
  if(props.type == FileType.Image) title.value ='选择图片'
  else title.value ='选择视频'
  query.value.page.index = 1
  query.value.entity.type = props.type
  query.value.entity.categoryId = 0
  query.value.entity.name = ''
  loadCategory()
  loadFile()
  selectCategory.value.id = 0
  selectCategory.value.name = '未分组'
  files.value = []
})
onMounted(() => {
  if(!commonStore.setting.fileDomain)
    commonStore.getSetting()
})

</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/formPage.scss";
.library {
  height: 540px;
}
.el-aside {
  width: 200px;
  
}
.category{
  width: 100%;
  display: flex;
  flex-direction:column;
  justify-content:center;
  ul {
    padding: 0;
    margin: 0;
    background-color: rgba(27,50,71,.04);
    border-radius: 4px;
    height: 454px;
    overflow-y: scroll;
    li {
        padding: 12px 8px;
        display: flex;
        justify-content:space-between;
        .name {
          text-align: left;
        }
        .count {
        text-align: right;
        } 
        .operation {
          text-align: right;
          .delete {
           width: 1em; 
           height: 1em; 
          }
          .editor { 
             width: 1em; 
             height: 1em; 
             margin-right: 5px;
            }
        }     
    }
    .active {
      display: flex;
      justify-content:space-between;
      align-items:center;
      background-color: #e6f7ff;
      color: #1890ff;

    }
  }
 
}
.list {
  padding: 0px;
  .title{
    .operation {
      color: #1890ff;
      margin-left: 5px;
    }
  }
}
.pointer {
  cursor:pointer;
}
.filelist{
         height: 434px;
          overflow-y: scroll;
          flex: 1;
          overflow-x: hidden;
          ul {
            display: flex;
            flex-wrap: wrap;
            margin-top: 15px;
            li {
              flex: 0 0 calc(16.6667% - 16px);
              margin-left: 16px;
              margin-bottom: 16px;
              position: relative;
              overflow-y: hidden;
              border: 1px solid #f0f0f0;
              box-sizing: border-box;
              .active {
                border: 1px solid #1890ff;
              }
              .el-image {
                width: 100%;
                height: 125px;
              }
              .el-checkbox {
                position: absolute;
                top: 32px;
                right: 0;
                bottom: 70px;
                left: 0;
                height: auto;
                border-radius: 0;
                padding: 0;
                .el-checkbox__input {
                  position: absolute;
                  top: 8px;
                  right: 8px;
                }
              }
              .number{
                padding: 0 10px;
                height: 30px;
                line-height: 30px;
                background: #0055DE;
                color: #ffff;
                position: absolute;
                right: 0;
                top: 0;
                font-size: 16px;
                
              }
              .icon-zoom {
                width: 1em;
                height: 1em;
                display: none;
                background: rgba(0, 0, 0, 0.04);
                position: absolute;
                left: 0;
                top: 0;
                font-size: 24px;
                padding: 4px;
                cursor: pointer;
                color: #8d8d8d;
              }
              &:hover .icon-zoom {
                display: block;
              }
              ::v-deep .el-checkbox {
                .el-checkbox__input {
                  position: absolute;
                  right: 8px;
                  top: -20px;
                }
                .el-checkbox__label {
                  position: absolute;
                  left: 32px;
                  top: -32px;
                  height: 32px;
                  right: 0;
                  font-size: 0;
                }
              }
              p {
                font-size: 14px;
                line-height: 36px;
                text-align: center;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                padding: 0 8px;
                // position: absolute
                // left: 0
                // right: 0
                // bottom: 36px
                // background-color: rgba(0, 0, 0, 0.04)
              }
              .el-button-group {
                height: 36px;
                line-height: 36px;
                display: flex;
                align-items: center;
                justify-content: space-between;
              }
            }
          }
} 
.filefooter{
  display: flex;
  justify-content:space-between;
  .operation {
    display: flex;
    width: 300px;
    align-items:center;
    .updatefile {
      margin-left: 10px;
     }
     .deletefile {
      margin-left: 10px;
     }
  }
}
::v-deep .el-upload-list__item-thumbnail {
  object-fit: scale-down;
}
</style>